﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Data;
using NRemedy;

namespace CMDBImportCIDLL
{
    public class Factory
    {
        public const string assemblyName = "NRemedy";
        public void ImportData(string server, string login, string password, Company company, DataTable dt, Sheet sheet, ShowMessageDelegate show, ImportOperator imoperator)
        {
            Assembly assembly = Assembly.Load("CMDBImportCIDLL");
            object modelIns = assembly.CreateInstance(string.Format("{0}.{1}", assemblyName, sheet.ModelName));

            Type xmlType = typeof(MapModelByXML<>).MakeGenericType(modelIns.GetType());
            MethodInfo xmlMethod = xmlType.GetMethod("MapExcelDataToModelByXML", BindingFlags.Public | BindingFlags.Static);
            object modelObj = xmlMethod.Invoke(null, new object[] { dt, sheet });
            if (sheet.Category != Category.RelationShip)
            {
                Type dtType = typeof(CommonDTOperate<>).MakeGenericType(modelIns.GetType());
                if (imoperator == ImportOperator.CreateAndUpdate)
                {
                    MethodInfo dtMethod = dtType.GetMethod("CreateAndUpdate", BindingFlags.Public | BindingFlags.Static);
                    dtMethod.Invoke(null, new object[] { server, login, password, company, modelObj, show });
                }
                else if (imoperator == ImportOperator.CreateSkipUpdate)
                {
                    MethodInfo dtMethod = dtType.GetMethod("CreateSkipUpdate", BindingFlags.Public | BindingFlags.Static);
                    dtMethod.Invoke(null, new object[] { server, login, password, company, modelObj, show });
                }
                else if (imoperator == ImportOperator.Delete)
                {
                    MethodInfo dtMethod = dtType.GetMethod("Delete", BindingFlags.Public | BindingFlags.Static);
                    dtMethod.Invoke(null, new object[] { server, login, password, company, modelObj, show });
                }
            }
            else
            {
                CommonDTShipOperate operate = new CommonDTShipOperate();
                operate.SaveAllRelationShipDT(server, login, password, company, (modelObj as List<RelationShipModel>), show);
            }
                
            //object resObj = dtMethod.Invoke(null, new object[] { modelObj, show });
            //return Convert.ToBoolean(resObj);
        }
    }
}
